﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using eSolution_HRMSS.Winforms;
using eSolution_HRMSS.UserControls;
using DevExpress.XtraEditors;
using Interface_Tier;
using Transfer_Object_Tier;
using System.Configuration;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;
using System.Drawing.Imaging;
using DevExpress.XtraTab;

namespace eSolution_HRMSS.Winforms
{
    public partial class FR_ThongTinNhanVien : DevExpress.XtraEditors.XtraForm
    {
        #region Khai báo interface
        IDIC_ALLOWANCEData _iallowance;
        IDIC_EDUCATIONData _iedu;
        ICommonCode _icommon;
        INhanVien _inhanvien;
        IHRM_EMPLOYEE_ALLOWANCEData _iempallowance;
        IDIC_DEGREEData _IDIC_DEGREEData;
        IDIC_ETHNICData _IDIC_ETHNICData;
        IDIC_HOSPITALData _IDIC_HOSPITALData;
        IDIC_INFORMATICData _IDIC_INFORMATICData;
        IDIC_JOBData _IDIC_JOBData;
        IDIC_LANGUAGEData _IDIC_LANGUAGEData;
        IDIC_NATIONALITYData _IDIC_NATIONALITYData;
        IDIC_POSITIONData _IDIC_POSITIONData;
        IDIC_PROFESSIONALData _IDIC_PROFESSIONALData;
        IDIC_RELATIVEData _IDIC_RELATIVEData;
        IDIC_RELIGIONData _IDIC_RELIGIONData;
        IDIC_SCHOOLData _IDIC_SCHOOLData;
        IDIC_SKILLData _IDIC_SKILLData;
        IHRM_BRANCHData _IHRM_BRANCHData;
        IHRM_DEPARTMENTData _IHRM_DEPARTMENTData;
        IHRM_GROUPData _IHRM_GROUPData; 
        IHRM_EMPLOYEE_RELATIVEData _IHRM_EMPLOYEE_RELATIVEData;
        IDIC_PROVINCEData _IDIC_PROVINCEData;
        IDIC_SALARY_STEPData _IDIC_SALARY_STEPData;
        IDIC_SALARY_RANKData _IDIC_SALARY_RANKData;
        IDIC_MINIMUMSALARYData _IDIC_MINIMUMSALARYData;
        IHRM_EMPLOYEE_DEGREEData _IHRM_EMPLOYEE_DEGREEData; 
        #endregion

        public delegate void updatelist();
        public updatelist truyentinhieu;

        eSolution_HRMSS.HRMSS_Ultil util = new HRMSS_Ultil();
        string ma_Nhan_Vien = "";
        string new_id = "";
        bool isUpdate = false;

        public FR_ThongTinNhanVien(bool _isUpdate)
        {
            InitializeComponent();
            isUpdate = _isUpdate;
        }
        
        public FR_ThongTinNhanVien(bool _isUpdate, string manv)
        {
            InitializeComponent();
            isUpdate = _isUpdate;
            ma_Nhan_Vien = manv;
            
        }

        private void FR_ThongTinNhanVien_Load(object sender, EventArgs e)
        {
            InterfaceRegistration();
            load_ds_cac_thong_tin_lookupedit();
            setactive_tab_page();
            
            tangid();

            if (isUpdate)
            {
                //load thong tin cua nhan vien de update
                load_thong_tin_nhan_vien();
                load_phu_cap_nhan_vien();
                load_quan_he();
                load_emp_degree();
            }
            else
            {
                txtmanv.Text = new_id;
            }
            
        }

        private void setactive_tab_page()
        {
            foreach (XtraTabPage t in xtraTabControl1.TabPages)
            {
                xtraTabControl1.SelectedTabPage = t;
            }
            xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
        }
        

        #region đăng ký interface

        private void InterfaceRegistration()
        {
            //dang ky de ket noi ung dung toi server do windows service quan ly
            _iallowance = (IDIC_ALLOWANCEData)Activator.GetObject(typeof(IDIC_ALLOWANCEData), util.Chuoiphucap);
            _iedu = (IDIC_EDUCATIONData)Activator.GetObject(typeof(IDIC_EDUCATIONData), util.Chuoihocvan);
            _icommon = (ICommonCode)Activator.GetObject(typeof(ICommonCode), util.Chuoicommon);
            _iempallowance = (IHRM_EMPLOYEE_ALLOWANCEData)Activator.GetObject(typeof(IHRM_EMPLOYEE_ALLOWANCEData), util.Chuoi_HRM_EMPLOYEE_ALLOWANCE);
            _IDIC_DEGREEData = (IDIC_DEGREEData)Activator.GetObject(typeof(IDIC_DEGREEData), util.Chuoibangcap);
            _IDIC_ETHNICData = (IDIC_ETHNICData)Activator.GetObject(typeof(IDIC_ETHNICData), util.Chuoidantoc);
            _IDIC_HOSPITALData = (IDIC_HOSPITALData)Activator.GetObject(typeof(IDIC_HOSPITALData), util.Chuoibv);
            _IDIC_INFORMATICData = (IDIC_INFORMATICData)Activator.GetObject(typeof(IDIC_INFORMATICData), util.Chuoitinhoc);
            _IDIC_JOBData = (IDIC_JOBData)Activator.GetObject(typeof(IDIC_JOBData), util.Chuoicongviec);
            _IDIC_LANGUAGEData = (IDIC_LANGUAGEData)Activator.GetObject(typeof(IDIC_LANGUAGEData), util.Chuoingoaingu);
            _IDIC_NATIONALITYData = (IDIC_NATIONALITYData)Activator.GetObject(typeof(IDIC_NATIONALITYData), util.Chuoiquoctich);
            _IDIC_POSITIONData = (IDIC_POSITIONData)Activator.GetObject(typeof(IDIC_POSITIONData), util.Chuoivitri);
            _IDIC_PROFESSIONALData = (IDIC_PROFESSIONALData)Activator.GetObject(typeof(IDIC_PROFESSIONALData), util.Chuoichuyenmon);
            _IDIC_RELATIVEData = (IDIC_RELATIVEData)Activator.GetObject(typeof(IDIC_RELATIVEData), util.Chuoiquanhegiadinh);
            _IDIC_RELIGIONData = (IDIC_RELIGIONData)Activator.GetObject(typeof(IDIC_RELIGIONData), util.Chuoitongiao);
            _IDIC_SCHOOLData = (IDIC_SCHOOLData)Activator.GetObject(typeof(IDIC_SCHOOLData), util.Chuoinoidaotao);
            _IHRM_EMPLOYEE_RELATIVEData = (IHRM_EMPLOYEE_RELATIVEData)Activator.GetObject(typeof(IHRM_EMPLOYEE_RELATIVEData), util.ChuoiHRM_EMPLOYEE_RELATIVEData);
            _inhanvien = (INhanVien)Activator.GetObject(typeof(INhanVien), util.Chuoinv);
            _IDIC_PROVINCEData = (IDIC_PROVINCEData)Activator.GetObject(typeof(IDIC_PROVINCEData), util.ChuoiDIC_PROVINCEData);
            _IDIC_SALARY_RANKData = (IDIC_SALARY_RANKData)Activator.GetObject(typeof(IDIC_SALARY_RANKData), util.ChuoiDIC_SALARY_RANKData);
            _IDIC_SALARY_STEPData = (IDIC_SALARY_STEPData)Activator.GetObject(typeof(IDIC_SALARY_RANKData), util.ChuoiDIC_SALARY_STEPData);
            _IHRM_BRANCHData = (IHRM_BRANCHData)Activator.GetObject(typeof(IHRM_BRANCHData), util.Chuoichinhanh);
            _IHRM_DEPARTMENTData = (IHRM_DEPARTMENTData)Activator.GetObject(typeof(IHRM_DEPARTMENTData), util.Chuoiphongban);
            _IHRM_GROUPData = (IHRM_GROUPData)Activator.GetObject(typeof(IHRM_GROUPData), util.ChuoiBT_HRM_GROUPData);
            _IDIC_MINIMUMSALARYData = (IDIC_MINIMUMSALARYData)Activator.GetObject(typeof(IDIC_MINIMUMSALARYData), util.ChuoiDIC_MINIMUMSALARYData);
            _IHRM_EMPLOYEE_DEGREEData = (IHRM_EMPLOYEE_DEGREEData)Activator.GetObject(typeof(IHRM_EMPLOYEE_DEGREEData), util.ChuoiEMPLOYEE_DEGREEData);
        }

        #endregion

        #region Load Thông tin combobox, gridview len form

        private void load_ds_cac_thong_tin_lookupedit()
        {
            load_ds_bang_cap();
            load_ds_chuyen_mon();
            load_ds_dan_toc();
            load_ds_hoc_van();
            load_ds_ngoai_ngu();
            load_ds_noi_dao_tao();
            load_ds_quoc_tich();
            load_ds_tin_hoc();
            load_ds_ton_giao();
            load_ds_chuc_vu();
            load_ds_chi_nhanh();
            load_ds_quan_he();
            load_phu_cap();
            set_default_datetime();
            load_ds_tinh();
            load_ds_ngachluong();
            
        }
        private void load_emp_degree()
        {
            foreach (CheckedListBoxItem item in chkcb_bangcap.Properties.GetItems())
            {
                string DegreeCode = item.Value.ToString();
                if (_IHRM_EMPLOYEE_DEGREEData.HRM_EMPLOYEE_DEGREE_Get(ma_Nhan_Vien, DegreeCode).Tables[0].Rows.Count>0)
                {
                    item.CheckState= CheckState.Checked;    
                }
            }

        }
        private void load_ds_ngachluong()
        {
            lu_ngachluong.Properties.DataSource = _IDIC_SALARY_RANKData.DIC_SALARY_RANK_GetList().Tables[0];
            lu_ngachluong.Properties.DisplayMember = "RankName";
            lu_ngachluong.Properties.ValueMember = "RankCode";
        }
        private void load_ds_bacluong(string rankcode)
        {
            lu_bacluong.Properties.DataSource = _IDIC_SALARY_STEPData.DIC_SALARY_STEP_GetListByRank(rankcode).Tables[0];
            lu_bacluong.Properties.DisplayMember = "StepName";
            lu_bacluong.Properties.ValueMember = "StepCode";
        }

        private void load_ds_tonhom(string DepartmentCode)
        {
            lu_tonhom.Properties.DataSource = _IHRM_GROUPData.HRM_GROUP_GetListByDepartmentCode(DepartmentCode).Tables[0];
            lu_tonhom.Properties.DisplayMember = "GroupName";
            lu_tonhom.Properties.ValueMember = "GroupCode";
        }

        private void load_ds_tinh()
        {
            lu_tinh.Properties.DataSource = _IDIC_PROVINCEData.DIC_PROVINCE_GetList().Tables[0];
            lu_tinh.Properties.DisplayMember = "ProvinceName";
            lu_tinh.Properties.ValueMember = "ProvinceCode";
        }
        private void lu_tinh_EditValueChanged(object sender, EventArgs e)
        {
            load_ds_bv();
        }
        private void load_ds_bv()
        {

            if (lu_tinh.EditValue != null)
            {
                string matinh = lu_tinh.EditValue.ToString();
                bhytbenhvien.Properties.DataSource = _IDIC_HOSPITALData.DIC_HOSPITAL_GetListByProvinceCode(matinh).Tables[0];
                bhytbenhvien.Properties.DisplayMember = "HospitalName";
                bhytbenhvien.Properties.ValueMember = "HospitalCode";
            }
            
        }
        private void load_quan_he() 
        {
            gridControl_nguoilienhe.DataSource = _IHRM_EMPLOYEE_RELATIVEData.HRM_EMPLOYEE_RELATIVE_GetList(ma_Nhan_Vien).Tables[0];
            gridControl_nguoilienhe.MainView.LayoutChanged();
        }
        private void load_phu_cap_nhan_vien() {
            
            DataTable dt = _iempallowance.HRM_EMPLOYEE_ALLOWANCE_GetList(txtmanv.Text).Tables[0];
            grdDSPhuCap.DataSource = dt;
            grdDSPhuCap.MainView.LayoutChanged();
        }
        private void load_phu_cap()
        {
            DataTable dt = _iallowance.DIC_ALLOWANCE_GetList().Tables[0];
            cbdsphucap_code.DataSource = dt;
            cbdsphucap_code.DisplayMember = "AllowanceCode";
            cbdsphucap_code.ValueMember = "AllowanceCode";

            cbdsphucap_name.DataSource = dt;
            cbdsphucap_name.DisplayMember = "AllowanceName";
            cbdsphucap_name.ValueMember = "AllowanceName";
        }

        private void load_ds_quan_he()
        {
            dsmoiquanhe.DataSource = _IDIC_RELATIVEData.DIC_RELATIVE_GetList().Tables[0];
            dsmoiquanhe.DisplayMember = "RelativeName";
            dsmoiquanhe.ValueMember = "RelativeName";
        }

        private void load_ds_quan_he_cua_nhan_vien(string manv)
        {
            load_ds_quan_he();
            gridControl_nguoilienhe.DataSource = _IHRM_EMPLOYEE_RELATIVEData.HRM_EMPLOYEE_RELATIVE_GetList(txtmanv.Text).Tables[0];
            gridControl_nguoilienhe.MainView.LayoutChanged();
        }

        private void load_ds_quoc_tich()
        {
            lu_quoctich.Properties.DataSource = _IDIC_NATIONALITYData.DIC_NATIONALITY_GetList().Tables[0];
            lu_quoctich.Properties.DisplayMember = "NationalityName";
            lu_quoctich.Properties.ValueMember = "NationalityCode";
        }

        private void load_ds_dan_toc()
        {
            lu_dantoc.Properties.DataSource = _IDIC_ETHNICData.DIC_ETHNIC_GetList().Tables[0];
            lu_dantoc.Properties.DisplayMember = "EthnicName";
            lu_dantoc.Properties.ValueMember = "EthnicCode";
        }

        private void load_ds_ton_giao()
        {
            lu_tongiao.Properties.DataSource = _IDIC_RELIGIONData.DIC_RELIGION_GetList().Tables[0];
            lu_tongiao.Properties.DisplayMember = "ReligionName";
            lu_tongiao.Properties.ValueMember = "ReligionCode";
        }

        private void load_ds_hoc_van()
        {
            lu_hocvan.Properties.DataSource = _iedu.DIC_EDUCATION_GetList().Tables[0];
            lu_hocvan.Properties.DisplayMember = "EducationName";
            lu_hocvan.Properties.ValueMember = "EducationCode";
        }

        private void load_ds_ngoai_ngu()
        {
            lu_ngoaingu.Properties.DataSource = _IDIC_LANGUAGEData.DIC_LANGUAGE_GetList().Tables[0];
            lu_ngoaingu.Properties.DisplayMember = "LanguageName";
            lu_ngoaingu.Properties.ValueMember = "LanguageCode";
        }

        private void load_ds_tin_hoc()
        {
            lu_tinhoc.Properties.DataSource = _IDIC_INFORMATICData.DIC_INFORMATIC_GetList().Tables[0];
            lu_tinhoc.Properties.DisplayMember = "InformaticName";
            lu_tinhoc.Properties.ValueMember = "InformaticCode";
        }

        private void load_ds_chuyen_mon()
        {
            lu_chuyenmon.Properties.DataSource = _IDIC_PROFESSIONALData.DIC_PROFESSIONAL_GetList().Tables[0];
            lu_chuyenmon.Properties.DisplayMember = "ProfessionalName";
            lu_chuyenmon.Properties.ValueMember = "ProfessionalCode";
        }

        private void load_ds_bang_cap()
        {
            chkcb_bangcap.Properties.DataSource = _IDIC_DEGREEData.DIC_DEGREE_GetList().Tables[0];
            chkcb_bangcap.Properties.DisplayMember = "DegreeName";
            chkcb_bangcap.Properties.ValueMember = "DegreeCode";
        }

        private void load_ds_noi_dao_tao()
        {
            lu_noidaotao.Properties.DataSource = _IDIC_SCHOOLData.DIC_SCHOOL_GetList().Tables[0];
            lu_noidaotao.Properties.DisplayMember = "SchoolName";
            lu_noidaotao.Properties.ValueMember = "SchoolCode";
        }

        private void load_ds_chuc_vu()
        {
            lu_chucvu.Properties.DataSource = _IDIC_POSITIONData.DIC_POSITION_GetList().Tables[0];
            lu_chucvu.Properties.DisplayMember = "PositionName";
            lu_chucvu.Properties.ValueMember = "PositionCode";
            
        }

        private void load_ds_chi_nhanh()
        {
            lu_chinhanh.Properties.DataSource = _IHRM_BRANCHData.HRM_BRANCH_GetList().Tables[0];
            lu_chinhanh.Properties.DisplayMember = "BranchName";
            lu_chinhanh.Properties.ValueMember = "BranchCode";
        }
        private void load_ds_phong_ban(string machinhanh)
        {
            lu_phongban.Properties.DataSource = _IHRM_DEPARTMENTData.HRM_DEPARTMENT_GetListByBranchCode(machinhanh).Tables[0];
            lu_phongban.Properties.DisplayMember = "DepartmentName";
            lu_phongban.Properties.ValueMember = "DepartmentCode";
        }
        private void load_ds_to_nhom(string maphongban)
        {
            lu_tonhom.Properties.DataSource = _IHRM_GROUPData.HRM_GROUP_GetListByDepartmentCode(maphongban).Tables[0];
            lu_tonhom.Properties.DisplayMember = "GroupName";
            lu_tonhom.Properties.ValueMember = "GroupCode";
        }

        private void set_default_datetime()
        {
            dtdenngay.DateTime = DateTime.Now;
            dtdenngayhochieu.DateTime = DateTime.Now;
            dtlvctngayketthuc.DateTime = DateTime.Now;
            dtlvctngaybatdau.DateTime = DateTime.Now;
            dtngaybatdau.DateTime = DateTime.Now;
            dtngaycap.DateTime = DateTime.Now;
            dtngaycaphochieu.DateTime = DateTime.Now;
            dtngaycapsold.DateTime = DateTime.Now;
            dtngaycaptkNH.DateTime = DateTime.Now;
            dtngayketthuc.DateTime = DateTime.Now;
            dtngayky.DateTime = DateTime.Now;
            dtngaynhapngu.DateTime = DateTime.Now;
            dtngaysinh.DateTime = DateTime.Now;
            dtngayvaodang.DateTime = DateTime.Now;
            dtngayvaodoan.DateTime = DateTime.Now;
            dtngayxuatngu.DateTime = DateTime.Now;
            dttungay.DateTime = DateTime.Now;
            bhxhdt_tinhtungay.DateTime = DateTime.Now;
            bhytdtdenngay.DateTime = DateTime.Now;
            bhytdttungay.DateTime = DateTime.Now;
            txttinhtungay.DateTime = DateTime.Now;
        }

        #endregion

        #region thêm xóa sửa thông tin nhân viên

        private HRM_EMPLOYEE Get_data_form()
        {
            HRM_EMPLOYEE nhanvien = new HRM_EMPLOYEE();
            nhanvien.EmployeeCode = txtmanv.Text;
            string BranchCode = Get_select_value_lookupedit(lu_chinhanh, "BranchCode");
            if (BranchCode != "")
            {
                nhanvien.BranchCode = BranchCode;
            }
            string DepartmentCode = Get_select_value_lookupedit(lu_phongban, "DepartmentCode");
            if (DepartmentCode != "")
            {
                nhanvien.DepartmentCode = DepartmentCode;
            }
            string GroupCode = Get_select_value_lookupedit(lu_tonhom, "GroupCode");
            if (GroupCode != "")
            {
                nhanvien.GroupCode = GroupCode;
            }
            nhanvien.CandidateCode = "";
            nhanvien.EnrollNumber = txtmachamcong.Text;
            nhanvien.FirstName = txtholot.Text;
            nhanvien.LastName = txtten.Text;
            nhanvien.Alias = txttenthuonggoi.Text;
            nhanvien.Sex = chknam.Checked;
            nhanvien.Marriage = cbtinhtranghonnhan.Text;
            nhanvien.Birthday = dtngaysinh.DateTime;
            nhanvien.BirthPlace = txtnoisinh.Text;
            nhanvien.MainAddress = txtdiachi.Text;
            nhanvien.ContactAddress = txttamtru.Text;
            nhanvien.CellPhone = txtdidong.Text;
            nhanvien.HomePhone = txtdtnha.Text;
            nhanvien.Email = txtemail.Text;
            nhanvien.Photo = util.ConvertImageToByteArray(imghinhdaidien.Image, ImageFormat.Jpeg);
            string Nationality = Get_select_value_lookupedit(lu_quoctich, "NationalityName");
            if (Nationality != "")
            {
                nhanvien.Nationality = Nationality;
            }
            string Ethnic = Get_select_value_lookupedit(lu_dantoc, "EthnicName");
            if (Ethnic != "")
            {
                nhanvien.Ethnic = Ethnic;
            }
            string Religion = Get_select_value_lookupedit(lu_tongiao, "ReligionName");
            if (Ethnic != "")
            {
                nhanvien.Religion = Religion;
            }
            string Education = Get_select_value_lookupedit(lu_hocvan, "EducationName");
            if (Education != "")
            {
                nhanvien.Education = Education;
            }
            string Language = Get_select_value_lookupedit(lu_ngoaingu, "LanguageName");
            if (Language != "")
            {
                nhanvien.Language = Language;
            }
            string Informatic = Get_select_value_lookupedit(lu_tinhoc, "InformaticName");
            if (Informatic != "")
            {
                nhanvien.Informatic = Informatic;
            }
            string Professional = Get_select_value_lookupedit(lu_chuyenmon, "ProfessionalName");
            if (Professional != "")
            {
                nhanvien.Professional = Professional;
            }
            string Position = Get_select_value_lookupedit(lu_chucvu, "PositionName");
            if (Position != "")
            {
                nhanvien.Position = Position;
            }
            string School = Get_select_value_lookupedit(lu_noidaotao, "SchoolName");
            if (School != "")
            {
                nhanvien.School = School;
            }
            nhanvien.IDCard = txtcmnd.Text;
            nhanvien.IDCardDate = dtngaycap.DateTime;
            nhanvien.IDCardPlace = txtnoicap.Text;
            nhanvien.IsTest = chkcothuviec.Checked;
            nhanvien.TestTime = txtthoigianthuviec.Text;
            nhanvien.TestFromDate = dttungay.DateTime;
            nhanvien.TestToDate = dtdenngay.DateTime;
            nhanvien.TestSalary = txtluongthuviec.Value;
            nhanvien.BeginDate = dtlvctngaybatdau.DateTime;
            if (cbtrangthainv.SelectedIndex==3)
                nhanvien.IsOffWork = true;
            else
                nhanvien.IsOffWork = false;
            nhanvien.EndDate = dtlvctngayketthuc.DateTime;
            nhanvien.Health = txtttsuckhoe.Text;
            nhanvien.Height = double.Parse(txtchieucao.Value.ToString());
            nhanvien.Weight = double.Parse(txtcannang.Value.ToString());
            nhanvien.PayForm = cbhinhthuctraluong.SelectedIndex;
            nhanvien.PayMoney = cbmucluong.Value;
            nhanvien.MinimumSalary = txtluongtoithieu.Value;

            string RankSalary = Get_select_value_lookupedit(lu_ngachluong, "RankCode");
            if (RankSalary != "")
            {
                nhanvien.RankSalary = RankSalary;
            }

            string StepSalary = Get_select_value_lookupedit(lu_bacluong, "StepCode");
            if (StepSalary != "")
            {
                nhanvien.StepSalary = int.Parse(StepSalary);
            }
            nhanvien.CoefficientSalary = double.Parse(txthesoluong.Value.ToString());
            nhanvien.DateSalary = txttinhtungay.DateTime;
            nhanvien.BasicSalary = txtmucluongcanban.Value;
            nhanvien.InsuranceSalary = txtluongdongbhxh.Value;

            nhanvien.Allowance1 = 0;
            nhanvien.Allowance2 = 0;
            nhanvien.Allowance3 = 0;
            nhanvien.Allowance4 = 0;

            nhanvien.IsSocialInsurance = chkbaohiemxahoi.Checked;
            nhanvien.IsHealthInsurance = chkbaohiemyte.Checked;
            nhanvien.IsUnemploymentInsurance = chkbaohiemthatnghiep.Checked;
            nhanvien.IsUnionMoney = chkphicongdoan.Checked;

            nhanvien.BankCode = txtsotk.Text;
            nhanvien.BankDate = dtngaycaptkNH.DateTime;
            nhanvien.BankName = txttenNH.Text;
            nhanvien.BankAddress = txtdiachiNH.Text;

            nhanvien.LaborCode = txtsolaodong.Text;
            nhanvien.LaborDate = dtngaycapsold.DateTime;
            nhanvien.LaborPlace = txtnoicapsold.Text;

            nhanvien.IsUnion = chkdavaodoan.Checked;
            nhanvien.UnionCode = txtsothedoan.Text;
            nhanvien.UnionDate = dtngayvaodoan.DateTime;
            nhanvien.UnionPlace = txtnoicapthedoan.Text;

            nhanvien.IsParty = chkdaladangvien.Checked;
            nhanvien.PartyCode = txtsothedang.Text;
            nhanvien.PartyDate = dtngayvaodang.DateTime;
            nhanvien.PartyPlace = txtnoicapthedang.Text;

            nhanvien.InsuranceCode = bhxhtxt_soso.Text;
            nhanvien.InsuranceDate = bhxhdt_tinhtungay.DateTime;
            nhanvien.InsurancePlace = bhxhtxtnoicap.Text;

            nhanvien.HealthInsuranceCode = bhytsoso.Text;
            nhanvien.HealthInsuranceFromDate = bhytdttungay.DateTime;
            nhanvien.HealthInsuranceToDate = bhytdtdenngay.DateTime;

            nhanvien.ContractCode = txtmahopdong.Text;
            nhanvien.ContractType = cbloaihopdong.Text;
            nhanvien.ContractSignDate = dtngayky.DateTime;
            nhanvien.ContractFromDate = dtngaybatdau.DateTime;
            nhanvien.ContractToDate = dtngayketthuc.DateTime;

            string Province = Get_select_value_lookupedit(lu_tinh, "ProvinceName");
            if (Province != "")
            {
                nhanvien.Province = Province;
            }
            string Hospital = Get_select_value_lookupedit(bhytbenhvien, "HospitalName");
            if (Hospital != "")
            {
                nhanvien.Hospital = Hospital;
            }

            nhanvien.MilitaryCode = txtsonghiavu.Text;
            nhanvien.MilitaryFromDate = dtngaynhapngu.DateTime;
            nhanvien.MilitaryToDate = dtngayxuatngu.DateTime;
            nhanvien.MilitaryPosition = txtchucvuquansu.Text;

            nhanvien.PassportCode = txtsohochieu.Text;
            nhanvien.PassportFromDate = dtngaycaphochieu.DateTime;
            nhanvien.PassportToDate = dtdenngayhochieu.DateTime;

            nhanvien.Status = cbtrangthainv.SelectedIndex;
            nhanvien.Account = txtusername.Text;
            nhanvien.Password = txtpass.Text;
            nhanvien.Description = txtghichu.Text;

            return nhanvien;
        }

        private void tangid()
        {
            new_id = _icommon.Generate_ID("HRM_EMPLOYEE", "EmployeeCode", "NV");
        }

        private int Nhan_Vien_insert()
        {
            return _inhanvien.NHAN_VIEN_THEM(Get_data_form());
        }

        private int Nhan_Vien_update()
        {
            return _inhanvien.NHAN_VIEN_CAP_NHAT(Get_data_form());
        }
        private int Them_Phu_Cap()
        {
            try
            {
                _iempallowance.HRM_EMPLOYEE_ALLOWANCE_Delete(txtmanv.Text);
            }
            catch (Exception)
            {
                
               return -1;
            }
            
            for (int i = 0; i < dsphucap.DataRowCount; i++)
            {
                string maphucap = dsphucap.GetRowCellValue(i, col_AllowanceCode).ToString();
                string sotien = dsphucap.GetRowCellValue(i, col_MaximumMoney).ToString();
                if (_iempallowance.HRM_EMPLOYEE_ALLOWANCE_Insert(txtmanv.Text, maphucap, decimal.Parse(sotien)) < 0)
                {
                    return -1;
                }
            }
            return 1;
        }
        private int Them_Moi_Quan_he()
        {
            try
            {
                _IHRM_EMPLOYEE_RELATIVEData.HRM_EMPLOYEE_RELATIVE_Delete(txtmanv.Text);
            }
            catch (Exception)
            {
                
                return -1;
            }
            for (int i = 0; i < gvdsnguoilienhe.DataRowCount; i++)
            {
                Guid personalID = Guid.NewGuid();
                string tennguoi = gvdsnguoilienhe.GetRowCellValue(i, col_hoten).ToString();
                string diachi = gvdsnguoilienhe.GetRowCellValue(i, col_diachi).ToString();
                string email = gvdsnguoilienhe.GetRowCellValue(i, col_email).ToString();
                string dienthoai = gvdsnguoilienhe.GetRowCellValue(i, col_sodt).ToString();
                string doituongphuthuoc = gvdsnguoilienhe.GetRowCellValue(i, col_doituongphuthuoc).ToString();
                string moiquanhe = gvdsnguoilienhe.GetRowCellValue(i, col_moiquanhe).ToString();
                bool dependen = false;
                if (doituongphuthuoc == "True")
                    dependen = true;

                if (_IHRM_EMPLOYEE_RELATIVEData.HRM_EMPLOYEE_RELATIVE_Insert(personalID,txtmanv.Text, tennguoi, moiquanhe, diachi, email, dienthoai, dependen) < 0)
                {
                    return -1;
                }
            }
            return 1;
        }
        private void them_bang_cap()
        {
            foreach (CheckedListBoxItem item in chkcb_bangcap.Properties.GetItems())
            {
                _IHRM_EMPLOYEE_DEGREEData.HRM_EMPLOYEE_DEGREE_Delete(txtmanv.Text, item.Value.ToString());
            }
            foreach (object item in chkcb_bangcap.Properties.GetItems().GetCheckedValues())
            {
                _IHRM_EMPLOYEE_DEGREEData.HRM_EMPLOYEE_DEGREE_Insert(txtmanv.Text, item.ToString());
            }
        }
        #endregion

        #region Load thông tin nhan vien len form
        private void load_thong_tin_nhan_vien()
        {
            DataTable dt = _inhanvien.LAY_THONG_TIN_NHAN_VIEN(ma_Nhan_Vien).Tables[0];
            if (dt.Rows.Count>0)
            {
                DataRow dr= dt.Rows[0];
                string BranchCode = dr["BranchCode"].ToString();
                string DepartmentCode = dr["DepartmentCode"].ToString();
                string GroupCode = dr["GroupCode"].ToString();
                string CandidateCode = dr["CandidateCode"].ToString();
                string EnrollNumber = dr["EnrollNumber"].ToString();
                string FirstName = dr["FirstName"].ToString();
                string LastName = dr["LastName"].ToString();
                string Alias = dr["Alias"].ToString();
                bool Sex = bool.Parse(dr["Sex"].ToString());
                string Marriage = dr["Marriage"].ToString();
                DateTime Birthday = DateTime.Parse(dr["Birthday"].ToString());
                string BirthPlace = dr["BirthPlace"].ToString();
                string MainAddress = dr["MainAddress"].ToString();
                string ContactAddress = dr["ContactAddress"].ToString();
                string CellPhone = dr["CellPhone"].ToString();
                string HomePhone = dr["HomePhone"].ToString();
                string Email = dr["Email"].ToString();
                byte[] Photo = null;
                if (dr["Photo"].ToString().Length>10)
                {
                    Photo = (byte[])dr["Photo"];
                    if (Photo.Length>10)
                    {
                        imghinhdaidien.Image = util.create_image_from_byte_string(Photo);
                    }
                }
                
                string Nationality = dr["Nationality"].ToString();
                string Ethnic = dr["Ethnic"].ToString();
                string Religion = dr["Religion"].ToString();
                string Education = dr["Education"].ToString();
                string Language = dr["Language"].ToString();
                string Informatic = dr["Informatic"].ToString();
                string Professional = dr["Professional"].ToString();
                string Position = dr["Position"].ToString();
                string School = dr["School"].ToString();
                string IDCard = dr["IDCard"].ToString();
                DateTime IDCardDate = DateTime.Parse(dr["IDCardDate"].ToString());
                string IDCardPlace = dr["IDCardPlace"].ToString();
                bool IsTest = bool.Parse(dr["IsTest"].ToString());
                string TestTime = dr["TestTime"].ToString();
                DateTime TestFromDate =DateTime.Parse( dr["TestFromDate"].ToString());
                DateTime TestToDate =DateTime.Parse( dr["TestToDate"].ToString());
                decimal TestSalary = decimal.Parse(dr["TestSalary"].ToString());
                DateTime BeginDate = DateTime.Parse(dr["BeginDate"].ToString());
                string IsOffWork = dr["IsOffWork"].ToString();
                DateTime EndDate = DateTime.Parse(dr["EndDate"].ToString());
                string Health = dr["Health"].ToString();
                decimal Height = decimal.Parse(dr["Height"].ToString());
                decimal Weight =decimal.Parse( dr["Weight"].ToString());
                string PayForm = dr["PayForm"].ToString();
                decimal PayMoney = decimal.Parse(dr["PayMoney"].ToString());
                decimal MinimumSalary = decimal.Parse(dr["MinimumSalary"].ToString());
                string RankSalary = dr["RankSalary"].ToString();
                string StepSalary = dr["StepSalary"].ToString();
                string CoefficientSalary = dr["CoefficientSalary"].ToString();
                DateTime DateSalary = DateTime.Parse(dr["DateSalary"].ToString());
                decimal BasicSalary = decimal.Parse(dr["BasicSalary"].ToString());
                decimal InsuranceSalary =decimal.Parse( dr["InsuranceSalary"].ToString());

                string Allowance1 = dr["Allowance1"].ToString();
                string Allowance2 = dr["Allowance2"].ToString();
                string Allowance3 = dr["Allowance3"].ToString();
                string Allowance4 = dr["Allowance4"].ToString();

                bool IsSocialInsurance = bool.Parse(dr["IsSocialInsurance"].ToString());
                bool IsHealthInsurance = bool.Parse(dr["IsHealthInsurance"].ToString());
                bool IsUnemploymentInsurance = bool.Parse(dr["IsUnemploymentInsurance"].ToString());
                bool IsUnionMoney = bool.Parse(dr["IsUnionMoney"].ToString());

                string BankCode = dr["BankCode"].ToString();
                DateTime BankDate =DateTime.Parse( dr["BankDate"].ToString());
                string BankName = dr["BankName"].ToString();
                string BankAddress = dr["BankAddress"].ToString();

                string LaborCode = dr["LaborCode"].ToString();
                DateTime LaborDate =DateTime.Parse( dr["LaborDate"].ToString());
                string LaborPlace = dr["LaborPlace"].ToString();

                bool IsUnion = bool.Parse(dr["IsUnion"].ToString());
                string UnionCode = dr["UnionCode"].ToString();
                DateTime UnionDate = DateTime.Parse(dr["UnionDate"].ToString());
                string UnionPlace = dr["UnionPlace"].ToString();

                bool IsParty = bool.Parse(dr["IsParty"].ToString());
                string PartyCode = dr["PartyCode"].ToString();
                DateTime PartyDate =DateTime.Parse( dr["PartyDate"].ToString());
                string PartyPlace = dr["PartyPlace"].ToString();

                string InsuranceCode = dr["InsuranceCode"].ToString();
                DateTime InsuranceDate = DateTime.Parse(dr["InsuranceDate"].ToString());
                string InsurancePlace = dr["InsurancePlace"].ToString();

                string HealthInsuranceCode = dr["HealthInsuranceCode"].ToString();
                DateTime HealthInsuranceFromDate =DateTime.Parse( dr["HealthInsuranceFromDate"].ToString());
                DateTime HealthInsuranceToDate = DateTime.Parse(dr["HealthInsuranceToDate"].ToString());
                string Province = dr["Province"].ToString();
                string Hospital = dr["Hospital"].ToString();

                string ContractCode = dr["ContractCode"].ToString();
                string ContractType = dr["ContractType"].ToString();
                DateTime ContractSignDate = DateTime.Parse(dr["ContractSignDate"].ToString());
                DateTime ContractFromDate = DateTime.Parse(dr["ContractFromDate"].ToString());
                DateTime ContractToDate = DateTime.Parse(dr["ContractToDate"].ToString());

                string MilitaryCode = dr["MilitaryCode"].ToString();
                DateTime MilitaryFromDate =  DateTime.Parse(dr["MilitaryFromDate"].ToString());
                DateTime MilitaryToDate = DateTime.Parse(dr["MilitaryToDate"].ToString());
                string MilitaryPosition = dr["MilitaryPosition"].ToString();

                string PassportCode = dr["PassportCode"].ToString();
                DateTime PassportFromDate =DateTime.Parse( dr["PassportFromDate"].ToString());
                DateTime PassportToDate = DateTime.Parse(dr["PassportToDate"].ToString());

                string Status = dr["Status"].ToString();
                string Account = dr["Account"].ToString();
                string Password = dr["Password"].ToString();
                string Description = dr["Description"].ToString();

                
                txtmanv.Text = ma_Nhan_Vien;
                txtten.Text = LastName;
                txtholot.Text = FirstName;
                chknam.Checked = Sex;
                dtngaysinh.DateTime = Birthday;
                txtnoisinh.Text = BirthPlace;
                cbtinhtranghonnhan.Text = Marriage;
                txtdiachi.Text = MainAddress;
                txttamtru.Text = ContactAddress;
                txtdidong.Text = CellPhone;
                txtdtnha.Text = HomePhone;
                txtemail.Text = Email;

                lu_quoctich.Text = Nationality;
                lu_dantoc.Text = Ethnic;
                lu_tongiao.Text = Religion;
                lu_hocvan.Text = Education;
                lu_ngoaingu.Text = Language;
                lu_tinhoc.Text = Informatic;
                lu_chuyenmon.Text = Professional;
                lu_noidaotao.Text = School;

                txtcmnd.Text = IDCard;
                txtnoicap.Text = IDCardPlace;
                dtngaycap.DateTime = IDCardDate;

                txtttsuckhoe.Text = Health;
                txtchieucao.Value = Height;
                txtcannang.Value = Weight;

                lu_chinhanh.EditValue = BranchCode;
                lu_phongban.EditValue = DepartmentCode;
                lu_tonhom.EditValue = GroupCode;
                lu_chucvu.Text=Position;
                lu_chucvu.CancelPopup();
                
                cbhinhthuctraluong.SelectedIndex = -1;
                cbhinhthuctraluong.SelectedIndex = int.Parse(PayForm);
                cbmucluong.Value = PayMoney;
                lu_ngachluong.EditValue = RankSalary;
                lu_bacluong.EditValue = int.Parse(StepSalary);
                txtluongtoithieu.Value = MinimumSalary;
                txthesoluong.Text = CoefficientSalary;
                txtmucluongcanban.Value = BasicSalary;
                txtluongdongbhxh.Value = InsuranceSalary;

                txtmachamcong.Text = EnrollNumber;
                txtghichu.Text = Description;
                txtusername.Text = Account;
                txtpass.Text = Password;

                chkbaohiemthatnghiep.Checked = IsUnemploymentInsurance;
                chkbaohiemxahoi.Checked = IsSocialInsurance;
                chkbaohiemyte.Checked = IsHealthInsurance;
                chkphicongdoan.Checked = IsUnionMoney;

                chkcothuviec.Checked = IsTest;
                txtthoigianthuviec.Text = TestTime;
                txtluongthuviec.Value = TestSalary;
                dttungay.DateTime = TestFromDate;
                dtdenngay.DateTime = TestToDate;

                dtlvctngaybatdau.DateTime = BeginDate;
                dtlvctngayketthuc.DateTime = EndDate;

                txtsotk.Text = BankCode;
                txttenNH.Text = BankName;
                txtdiachiNH.Text = BankAddress;
                dtngaycaptkNH.DateTime = BankDate;

                chkdavaodoan.Checked = IsUnion;
                txtsothedoan.Text = UnionCode;
                dtngayvaodoan.DateTime = UnionDate;
                txtnoicapthedoan.Text = UnionPlace;

                chkdaladangvien.Checked = IsParty;
                txtsothedang.Text = PartyCode;
                txtnoicapthedang.Text = PartyPlace;
                dtngayvaodang.DateTime = PartyDate;

                txtsonghiavu.Text = MilitaryCode;
                dtngaynhapngu.DateTime = MilitaryFromDate;
                dtngayxuatngu.DateTime = MilitaryToDate;
                txtchucvuquansu.Text = MilitaryPosition;

                txtsohochieu.Text = PassportCode;
                dtngaycaphochieu.DateTime = PassportFromDate;
                dtdenngayhochieu.DateTime = PassportToDate;

                txtsolaodong.Text = LaborCode;
                dtngaycapsold.DateTime = LaborDate;
                txtnoicapsold.Text = LaborPlace;

                bhxhtxt_soso.Text = InsuranceCode;
                bhxhdt_tinhtungay.DateTime = InsuranceDate;
                bhxhtxtnoicap.Text = InsurancePlace;

                bhytbenhvien.Text = Hospital;
                bhytdtdenngay.DateTime = HealthInsuranceToDate;
                bhytdttungay.DateTime = HealthInsuranceFromDate;
                bhytsoso.Text = HealthInsuranceCode;

                txtmahopdong.Text = ContractCode;
                cbloaihopdong.Text = ContractType;
                dtngaybatdau.DateTime = ContractFromDate;
                dtngayketthuc.DateTime = ContractToDate;
                dtngayky.DateTime = ContractSignDate;

                this.Text = "Thông tin nhân viên - "+FirstName + " " + LastName;
            }
        }
        #endregion

        #region Sự kiện button click
        private void btluudong_Click(object sender, EventArgs e)
        {
            if (!validate_data())
            {
                MessageBox.Show("Vui lòng nhập đầy đủ các thông tin có dấu (*)");
                return;
            }

            if (!isUpdate)
            {
                //insert
                if (Nhan_Vien_insert() >= 0)
                {
                    Them_Phu_Cap();
                    Them_Moi_Quan_he();
                    them_bang_cap();
                    truyentinhieu();
                    this.Close();
                }
                else
                    MessageBox.Show(util.Loithaotac);
            }
            else
            {
                //update
                if (Nhan_Vien_update() >= 0)
                {
                    Them_Phu_Cap();
                    Them_Moi_Quan_he();
                    them_bang_cap();
                    truyentinhieu();
                    this.Close();
                }
                else
                    MessageBox.Show(util.Loithaotac);
            }
        }

        private bool validate_data()
        {
            if (txtholot.Text.Length == 0)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
                dxErrorProvider1.SetError(txtholot, util.Loi_botrong);
                return false;
            }
            if (txtten.Text.Length == 0)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
                dxErrorProvider1.SetError(txtten, util.Loi_botrong);
                return false;
            }
            if ((DateTime.Now.Year- dtngaysinh.DateTime.Year)<18)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
                dxErrorProvider1.SetError(dtngaysinh, util.Loi_tuoiduoi18);
                return false;
            }
            if (txtnoisinh.Text.Length == 0)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
                dxErrorProvider1.SetError(txtnoisinh, util.Loi_botrong);
                return false;
            }
            if (txtdiachi.Text.Length == 0)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[0];
                dxErrorProvider1.SetError(txtdiachi, util.Loi_botrong);
                return false;
            }
            if (lu_chinhanh.EditValue==null)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[1];
                dxErrorProvider1.SetError(lu_chinhanh, util.Loi_botrong);
                return false;
            }
            if (lu_phongban.EditValue == null)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[1];
                dxErrorProvider1.SetError(lu_phongban, util.Loi_botrong);
                return false;
            }
            if (lu_chucvu.EditValue == null)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[1];
                dxErrorProvider1.SetError(lu_chucvu, util.Loi_botrong);
                return false;
            }
            if (cbhinhthuctraluong.SelectedIndex==1 && cbmucluong.Value<=0)
            {
                xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages[1];
                dxErrorProvider1.SetError(lu_chucvu, util.Loisoam);
                return false;
            }
            return true;
        }

        private void clear_form()
        {
            this.Text = "Thông tin nhân viên";
            tangid();
            txtmanv.Text = new_id;
            txtten.Text = "";
            txtholot.Text = "";
            chknam.Checked = false;
            dtngaysinh.DateTime = DateTime.Now;
            txtnoisinh.Text = "";
            cbtinhtranghonnhan.Text = "";
            txtdiachi.Text = "";
            txttamtru.Text = "";
            txtdidong.Text = "";
            txtdtnha.Text = "";
            txtemail.Text = "";
            imghinhdaidien.Image = null;

            lu_quoctich.EditValue = null;
            lu_dantoc.EditValue = null;
            lu_tongiao.EditValue = null;
            lu_hocvan.EditValue = null;
            lu_ngoaingu.EditValue = null;
            lu_tinhoc.EditValue = null;
            lu_chuyenmon.EditValue = null;
            lu_noidaotao.EditValue = null;
            foreach (CheckedListBoxItem item in chkcb_bangcap.Properties.GetItems())
            {
                item.CheckState = CheckState.Unchecked;
            }

            txtcmnd.Text = "";
            txtnoicap.Text = "";
            dtngaycap.DateTime = DateTime.Now;

            txtttsuckhoe.Text = "";
            txtchieucao.Text = "";
            txtcannang.Text = "";

            lu_chinhanh.EditValue = null;
            lu_phongban.EditValue = null;
            lu_tonhom.EditValue = null;
            lu_chucvu.EditValue = null;

            cbhinhthuctraluong.SelectedIndex = 1;
            cbmucluong.Text = "0";
            lu_ngachluong.EditValue = null;
            lu_bacluong.EditValue = null;
            txtluongtoithieu.Text= "0";
            txthesoluong.Text = "0";
            txtmucluongcanban.Text = "0";
            txtluongdongbhxh.Text = "0";

            txtmachamcong.Text = "";
            txtghichu.Text = "";
            txtusername.Text = "";
            txtpass.Text = "";

            chkbaohiemthatnghiep.Checked = false;
            chkbaohiemxahoi.Checked = false;
            chkbaohiemyte.Checked = false;
            chkphicongdoan.Checked = false;

            chkcothuviec.Checked = false;
            txtthoigianthuviec.Text = "";
            txtluongthuviec.Text = "";
            dttungay.DateTime = DateTime.Now;
            dtdenngay.DateTime = DateTime.Now;

            dtlvctngaybatdau.DateTime = DateTime.Now;
            dtlvctngayketthuc.DateTime = DateTime.Now;

            txtsotk.Text = "";
            txttenNH.Text = "";
            txtdiachiNH.Text = "";
            dtngaycaptkNH.DateTime = DateTime.Now;

            chkdavaodoan.Checked = false;
            txtsothedoan.Text = "";
            dtngayvaodoan.DateTime = DateTime.Now;
            txtnoicapthedoan.Text = "";

            chkdaladangvien.Checked = false;
            txtsothedang.Text = "";
            txtnoicapthedang.Text = "";
            dtngayvaodang.DateTime = DateTime.Now;

            txtsonghiavu.Text = "";
            dtngaynhapngu.DateTime = DateTime.Now;
            dtngayxuatngu.DateTime = DateTime.Now;
            txtchucvuquansu.Text = "";

            txtsohochieu.Text = "";
            dtngaycaphochieu.DateTime = DateTime.Now;
            dtdenngayhochieu.DateTime = DateTime.Now;

            txtsolaodong.Text = "";
            dtngaycapsold.DateTime = DateTime.Now;
            txtnoicapsold.Text = "";

            bhxhtxt_soso.Text = "";
            bhxhdt_tinhtungay.DateTime = DateTime.Now;
            bhxhtxtnoicap.Text = "";

            bhytbenhvien.Text = "";
            bhytdtdenngay.DateTime = DateTime.Now;
            bhytdttungay.DateTime = DateTime.Now;
            bhytsoso.Text = "";

            txtmahopdong.Text = "";
            cbloaihopdong.Text = "";
            dtngaybatdau.DateTime = DateTime.Now;
            dtngayketthuc.DateTime = DateTime.Now;
            dtngayky.DateTime = DateTime.Now;
            isUpdate = false;

            load_phu_cap_nhan_vien();
            load_ds_quan_he_cua_nhan_vien(txtmanv.Text);

        }
        private void btluuthem_Click_1(object sender, EventArgs e)
        {
            if (!validate_data())
            {
                MessageBox.Show("Vui lòng nhập đầy đủ các thông tin có dấu (*)");
                return;
            }

            if (!isUpdate)
            {
                //insert
                if (Nhan_Vien_insert() >= 0)
                {
                    Them_Phu_Cap();
                    Them_Moi_Quan_he();
                    them_bang_cap();
                    truyentinhieu();
                    clear_form();
                }
                else
                    MessageBox.Show(util.Loithaotac);
            }
            else
            {
                //update
                if (Nhan_Vien_update() >= 0)
                {
                    Them_Phu_Cap();
                    Them_Moi_Quan_he();
                    them_bang_cap();
                    truyentinhieu();
                    clear_form();
                }
                else
                    MessageBox.Show(util.Loithaotac);
            }
        }

        private void btdong_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region quản lý phụ cấp cho nhan viên
        private void cbdsphucap_EditValueChanged(object sender, EventArgs e)
        {
            GridLookUpEdit editor = (dsphucap.ActiveEditor as GridLookUpEdit);
            if (editor != null)
            {
                if (dsphucap.ValidateEditor())
                {
                    lookupchanged(sender);
                }
            }
        }

        private void cbdsphucap_name_EditValueChanged(object sender, EventArgs e)
        {
            GridLookUpEdit editor = (dsphucap.ActiveEditor as GridLookUpEdit);
            if (editor != null)
            {
                if (dsphucap.ValidateEditor())
                {
                    lookupchanged(sender);
                }
            }
        }

        private bool is_duplicate(string new_value, GridView gview, object sender, string column_name)
        {
            GridView view = sender as GridView;
            DataView dataView = view.DataSource as DataView;
            System.Collections.IEnumerator en = dataView.GetEnumerator();
            en.Reset();
            while (en.MoveNext())
            {
                DataRowView row = en.Current as DataRowView;
                if (((DataRowView)gview.GetFocusedRow()) != row)
                {
                    object colValue = row[column_name];
                    if (colValue.ToString()==new_value)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void lookupchanged(object sender)
        {
            GridLookUpEdit editor = (sender as GridLookUpEdit);
            GridView view = editor.Properties.View as GridView;
            object code_val = view.GetRowCellValue(view.FocusedRowHandle, "AllowanceCode");
            object name_val = view.GetRowCellValue(view.FocusedRowHandle, "AllowanceName");
            object money_val = view.GetRowCellValue(view.FocusedRowHandle, "MaximumMoney");

            dsphucap.SetRowCellValue(dsphucap.FocusedRowHandle, col_AllowanceCode, code_val);
            dsphucap.SetRowCellValue(dsphucap.FocusedRowHandle, col_AllowanceName, name_val);
            dsphucap.SetRowCellValue(dsphucap.FocusedRowHandle, col_MaximumMoney, money_val);
        }

        private void dsbangcap_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
        {
            
            GridView view = sender as GridView;
            if (view.FocusedColumn.FieldName == "AllowanceCode")
            {
                string AllowanceCode = Convert.ToString(e.Value);
                if (is_duplicate(AllowanceCode, dsphucap, sender, "AllowanceCode"))
                {
                    //đã co tren luoi
                    e.Valid = false;
                    e.ErrorText = util.Loitontai;
                }

            }
            else if (view.FocusedColumn.FieldName == "AllowanceName")
            {

                string AllowanceName = Convert.ToString(e.Value);
                if (is_duplicate(AllowanceName, dsphucap, sender, "AllowanceName"))
                {
                    //đã co tren luoi
                    e.Valid = false;
                    e.ErrorText = util.Loitontai;
                }
                
            }
            else
            {
                double money = Convert.ToDouble(e.Value);
                if (money < 0)
                {
                    e.Valid = false;
                    e.ErrorText = util.Loisoam;
                }
                else
                {
                    string val = view.GetFocusedRowCellValue(col_AllowanceCode).ToString();
                    if (val=="" || val==null)
                    {
                        e.Valid = false;
                        e.ErrorText = string.Format(util.Vuilongchonmot, "phụ cấp");
                    }
                }
            }
        }

        private void dsbangcap_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.DisplayError;
        }
        #endregion

        private string Get_select_value_lookupedit(LookUpEdit lu_edit, string column_name)
        {
            object row = lu_edit.Properties.GetDataSourceRowByKeyValue(lu_edit.EditValue);
            if (row != null)
            {
                string value = ((DataRowView)row)[column_name].ToString();
                return value;
            }

            return "";
        }
        private void lu_chinhanh_EditValueChanged(object sender, EventArgs e)
        {
            if (lu_chinhanh.EditValue == null)
            {
                return;
            }
            //lay muc luong toi thieu
            string minimumsalary = Get_select_value_lookupedit(lu_chinhanh, "MinimumSalary");
            txtluongtoithieu.Value = decimal.Parse(minimumsalary);

            string BranchCode = lu_chinhanh.EditValue.ToString();
            if (BranchCode != "")
            {
                load_ds_phong_ban(BranchCode);
            }
        }

        private void lu_phongban_EditValueChanged(object sender, EventArgs e)
        {
            if (lu_phongban.EditValue == null)
            {
                return;
            }
            string DeptCode = lu_phongban.EditValue.ToString();
            if (DeptCode != "")
            {
                load_ds_to_nhom(DeptCode);
            }
        }

        private void simpleButton13_Click(object sender, EventArgs e)
        {
            FR_Hospital bv = new FR_Hospital();
            bv.truyentinhieu = new FR_Hospital.updatelist(load_ds_bv);
            bv.ShowDialog(this);
        }

        private void simpleButton14_Click(object sender, EventArgs e)
        {

        }

        private void lu_ngachluong_EditValueChanged(object sender, EventArgs e)
        {
            if (lu_ngachluong.EditValue==null)
            {
                return;
            }
            string RankCode = lu_ngachluong.EditValue.ToString();
            if (RankCode != "")
            {
                load_ds_bacluong(RankCode);
            }
        }


        private void lu_bacluong_EditValueChanged(object sender, EventArgs e)
        {
            if (lu_bacluong.EditValue!=null)
            {
                tinh_luong();
                
            }
        }

        private void tinh_luong()
        {

            //DataRow dr=_IDIC_MINIMUMSALARYData.DIC_MINIMUMSALARY_GetList().Tables[0].Rows[0];
            decimal minimunSalary = txtluongtoithieu.Value;//decimal.Parse(dr["Money"].ToString());
            decimal Coefficient = decimal.Parse(Get_select_value_lookupedit(lu_bacluong, "Coefficient"));
            txthesoluong.Value = Coefficient;
            //txtluongtoithieu.Value = minimunSalary;
            txtmucluongcanban.Value = minimunSalary * Coefficient;
            if (!isUpdate)
            {
                txtluongdongbhxh.Value = minimunSalary * Coefficient;
            }
        }

        private void cbhinhthuctraluong_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbhinhthuctraluong.SelectedIndex == 0)
            {
                cbmucluong.Properties.ReadOnly = true;
                txtluongdongbhxh.Value = txtmucluongcanban.Value;
                lu_bacluong.Properties.ReadOnly = false;
                lu_ngachluong.Properties.ReadOnly = false;
            }
            else
            {
                cbmucluong.Properties.ReadOnly = false;
                lu_bacluong.EditValue = null;
                lu_ngachluong.EditValue = null;
                lu_bacluong.Properties.ReadOnly = true;
                lu_ngachluong.Properties.ReadOnly = true;
                txtluongdongbhxh.Value = cbmucluong.Value;
            }
        }
        #region khu vuc them nhanh danh muc

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_QuocTich quoctich = new DanhMuc.FR_QuocTich(false);
            quoctich.truyentinhieu = new DanhMuc.FR_QuocTich.updatelist(load_ds_quoc_tich);
            quoctich.ShowDialog(this);
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_TonGiao tongiao = new DanhMuc.FR_TonGiao(false);
            tongiao.truyentinhieu = new DanhMuc.FR_TonGiao.updatelist(load_ds_ton_giao);
            tongiao.ShowDialog(this);
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_NgoaiNgu ngoaingu = new DanhMuc.FR_NgoaiNgu(false);
            ngoaingu.truyentinhieu = new DanhMuc.FR_NgoaiNgu.updatelist(load_ds_ngoai_ngu);
            ngoaingu.ShowDialog(this);
        }

        #endregion

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_ChuyenMon chuyenmon = new DanhMuc.FR_ChuyenMon(false);
            chuyenmon.truyentinhieu = new DanhMuc.FR_ChuyenMon.updatelist(load_ds_chuyen_mon);
            chuyenmon.ShowDialog(this);
        }

        private void simpleButton8_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_DanToc dantoc = new DanhMuc.FR_DanToc(false);
            dantoc.truyentinhieu = new DanhMuc.FR_DanToc.updatelist(load_ds_dan_toc);
            dantoc.ShowDialog(this);
        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_HocVan hocvan = new DanhMuc.FR_HocVan(false);
            hocvan.truyentinhieu = new DanhMuc.FR_HocVan.updatelist(load_ds_hoc_van);
            hocvan.ShowDialog(this);
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_TinHoc tinhoc = new DanhMuc.FR_TinHoc(false);
            tinhoc.truyentinhieu = new DanhMuc.FR_TinHoc.updatelist(load_ds_tin_hoc);
            tinhoc.ShowDialog(this);
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_BangCap tinhoc = new DanhMuc.FR_BangCap(false);
            tinhoc.truyentinhieu = new DanhMuc.FR_BangCap.updatelist(load_ds_bang_cap);
            tinhoc.ShowDialog(this);
        }

        private void simpleButton9_Click(object sender, EventArgs e)
        {
            FR_NoiDaoTao daotao = new FR_NoiDaoTao();
            daotao.truyentinhieu = new FR_NoiDaoTao.updatelist(load_ds_noi_dao_tao);
            daotao.ShowDialog(this);
        }

        private void simpleButton21_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_ChiNhanh daotao = new DanhMuc.FR_ChiNhanh(false);
            daotao.truyentinhieu = new DanhMuc.FR_ChiNhanh.updatelist(load_ds_chi_nhanh);
            daotao.ShowDialog(this);
        }
        private void update_ds_phong_ban()
        {
            if (lu_chinhanh.EditValue!=null)
            {
                load_ds_phong_ban(lu_chinhanh.EditValue.ToString());
            }
        }
        private void simpleButton22_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_PhongBan daotao = new DanhMuc.FR_PhongBan(false);
            daotao.truyentinhieu = new DanhMuc.FR_PhongBan.updatelist(update_ds_phong_ban);
            daotao.ShowDialog(this);
        }
        private void update_ds_to_nhom()
        {
            if (lu_phongban.EditValue != null)
            {
                load_ds_to_nhom(lu_phongban.EditValue.ToString());
            }
        }
        private void simpleButton20_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_ToNhom daotao = new DanhMuc.FR_ToNhom(false);
            daotao.truyentinhieu = new DanhMuc.FR_ToNhom.updatelist(update_ds_to_nhom);
            daotao.ShowDialog(this);
        }

        private void simpleButton19_Click(object sender, EventArgs e)
        {
            DanhMuc.FR_ChucVu daotao = new DanhMuc.FR_ChucVu(false);
            daotao.truyentinhieu = new DanhMuc.FR_ChucVu.updatelist(load_ds_chuc_vu);
            daotao.ShowDialog(this);
        }

        private void simpleButton16_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton17_Click(object sender, EventArgs e)
        {

        }



    }
}